<template>
    <div class="fillcontain">
        <!-- <head-top></head-top> -->
        <div class="table_container" >
            <el-collapse v-model="activeNames" accordion>
            <el-collapse-item title="查询条件" name="1">

                <el-row :gutter="20">
                    <el-col :span="20">
                        <div class="demo-input-suffix" >
                            <el-input
                                placeholder="请输入优惠券名称"
                                prefix-icon="el-icon-search"
                                v-model="rulename">
                            </el-input>  
                            <el-select v-model="type" clearable placeholder="请选择优惠券类型">
                                <el-option
                                v-for="item in statuslist"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>        
                        </div>
                    </el-col>
                    <el-col :span="4" >
                        <div style="text-align:right">
                        <el-button type="primary" icon="el-icon-search" :loading="searchLoading" @click="doSearch()" >查询</el-button>
                        </div>
                    </el-col>
                </el-row>    
            </el-collapse-item>
            </el-collapse>
        </div>
        <div class="table_container" >

            <el-row :gutter="10">
                <el-col :span="20">
                    <div class="demo-input-suffix" >
                               
                    </div>
                </el-col>
                <el-col :span="4" >
                    <div style="text-align:right">
                    <el-button round type="primary" icon="el-icon-plus" size="mini" @click="doAdd()" >添加</el-button>
                    </div>
                </el-col>
            </el-row>    
            
        </div>        
        <div class="table_container">
            <el-table
                :data="tableData"
                style="width: 100%" stripe>
                <el-table-column type="expand">
                  <template scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                      <el-form-item label="优惠券ID">
                        <span>{{ props.row.id }}</span>
                      </el-form-item>
                      <el-form-item label="优惠券名称">
                        <span>{{ props.row.yhqmc }}</span>
                      </el-form-item>
                      <el-form-item label="开始日期" >
                        <span>{{ props.row.ksrq }}</span>
                      </el-form-item>
                      <el-form-item label="结束日期">
                        <span>{{ props.row.jsrq }}</span>
                      </el-form-item>                                            
                      <el-form-item label="类型">
                        <span>{{ props.row.typename }}</span>
                      </el-form-item>
                      <el-form-item label="内容">
                        <span>{{ props.row.content }}</span>
                      </el-form-item>                                          
                      <el-form-item label="有余额标记">
                        <el-checkbox v-model="props.row.bMulti_flag" disabled > </el-checkbox>
                      </el-form-item>
                      <el-form-item label="状态">
                        <span>{{ props.row.statusname }}</span>
                      </el-form-item>                                                               
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column label="优惠券ID"  prop="id"></el-table-column>
                <el-table-column  label="优惠券名称" prop="yhqmc"></el-table-column>
                <el-table-column label="类型" prop="typename"></el-table-column>
                <el-table-column  label="有余额标记">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.bMulti_flag" disabled > </el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="内容" prop="content"></el-table-column>
                <el-table-column label="状态" prop="statusname"></el-table-column>
                <el-table-column label="操作" width="200">
                 <!--  <template scope="scope">
                    <el-button
                      size="mini"
                      @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  </template> -->
                  <template slot-scope="scope">
                        <el-dropdown >
                        <span class="el-dropdown-link">
                             <i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="edit" @click.native="handleEdit(scope.$index, scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item command="start" divided :disabled="scope.row.status==1"  @click.native="handleDisabled(scope.$index, scope.row,1)">启用</el-dropdown-item>
                            <el-dropdown-item command="end" :disabled="scope.row.status==2"  @click.native="handleDisabled(scope.$index, scope.row,2)">禁用</el-dropdown-item>
                            <el-dropdown-item command="del" divided :disabled="scope.row.status>0"  @click.native="handleDelete(scope.$index, scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                        </el-dropdown>
                   </template>
                </el-table-column>
            </el-table>
            <div class="Pagination">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-size="20"
                  layout="total, prev, pager, next"
                  :total="count">
                </el-pagination>
            </div>
            <el-dialog title="修改优惠券发放规则" v-model="dialogFormVisible" :visible.sync="dialogFormVisible">
                <el-form :model="selectTable" :rules="rules" ref="editForm">
                    <el-form-item label="优惠券名称" label-width="100px" prop="yhqmc">
                        <el-input v-model="selectTable.yhqmc" auto-complete="off" placeholder="必填项" ></el-input>
                    </el-form-item>
                    <el-form-item label="返券限额" label-width="100px">
                        <el-input v-model="selectTable.grantmoney_max" auto-complete="off"></el-input>
                    </el-form-item>                    
                    <el-form-item label=" " label-width="100px">
                         <el-checkbox v-model="selectTable.bLJ" >累计返券</el-checkbox>
                          <el-checkbox v-model="selectTable.bLadder" >阶梯返券</el-checkbox>
                    </el-form-item>
 
                    <el-form-item label="状态" label-width="100px">
                        <el-select v-model="selectTable.status" disabled>
                            <el-option
                            v-for="item in statuslist"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>                    
                    </el-form-item>
                    <el-form-item label="金额规则" label-width="100px">
                        <el-table :data="tableDataItem" style="width: 100%" stripe  border>
                            <el-table-column label="消费金额">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.salemoney" auto-complete="off"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column  label="返券金额">
                                <template slot-scope="scope">
                                   <el-input v-model="scope.row.grantmoney" auto-complete="off"></el-input>
                                </template>
                            </el-table-column>              
                        </el-table>
                    </el-form-item>                   
                </el-form>
              <div slot="footer" class="dialog-footer">
                  <el-button type="success" icon="el-icon-plus" @click="AddRule">新增规则</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRule">确 定</el-button>
              </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import headTop from '../components/headTop'
    import {baseUrl, baseImgPath} from '@/config/env'
    import { getCoupDefLists,saveCoupGrantRuleLists,getCoupGrantRuleItem,deleteCoupGrantRule,disableCoupGrantRule} from '@/api/getData'
    export default {
        data(){
            return {
                baseUrl,
                baseImgPath,
                searchLoading:false,
                activeNames: ['1'],
                type:'',
                statuslist:[{
                    value: '1',
                    label: '钱买券'
                    }, {
                    value: '2',
                    label: '普通券'
                    }, {
                    value: '3',
                    label: '商铺券'
                    }, {
                    value: '4',
                    label: '异业联盟券'
                    }, {
                    value: '5',
                    label: '消金券'
                    }
                ],
                rules : {
                    yhqmc : [
                        { required: true, message: '请输入优惠券名称', trigger: 'blur' }
                    ]
                },                
                curId:null,
                selectIndex: null,
                city: {},
                offset: 0,
                limit: 20,
                count: 0,
                tableData: [],
                tableDataItem: [],
                currentPage: 1,
                selectTable: {},
                dialogFormVisible: false,
                categoryOptions: [],
                selectedCategory: [],
                address: {},
                rulename:''
            }
        },
        created(){
            this.initData();
        },
    	components: {
    		headTop,
    	},
        methods: {
            async initData(){
                try{
                /*     this.city = await cityGuess();
                    const countData = await getResturantsCount();
                    if (countData.status == 1) {
                        this.count = countData.count;
                    }else{
                        throw new Error('获取数据失败');
                    } */
                    this.doGetCoupDefLists();
                }catch(err){
                    console.log('获取数据失败', err);
                }
            },
            
            async doGetCoupDefLists(){
                var _this = this
                var data = {
                    page:_this.currentPage,
                    rows:_this.limit,
                    yhqname:_this.yhqname,
                    type:_this.type
                }
                const lists = await getCoupDefLists(data);
                this.tableData = [];
                _this.count = lists.total
                lists.rows.forEach(item => {
                    const tableData = {};
                    tableData.id = item.id;
                    tableData.yhqid = item.yhqid;
                    tableData.yhqmc = item.yhqmc;
                    tableData.type = item.type;
                    tableData.typename = item.typename;
                    tableData.title = item.title;
                    tableData.fee = item.fee;
                    tableData.content = item.content;
                    tableData.ksrq = item.ksrq.split(" ",1)[0];
                    tableData.jsrq = item.jsrq.split(" ",1)[0];
                    tableData.weixinmc = item.weixinmc;
                    tableData.weixincontent = item.weixincontent;
                    tableData.photopath = item.photopath;
                    tableData.photopath2 = item.photopath2;
                    tableData.bMulti_flag = (item.multi_flag==1)?true:false;
                    tableData.multi_flag = item.multi_flag;
                    tableData.zxrate = item.zxrate;
                    tableData.zxvalue = item.zxvalue;
                    tableData.statusname = item.statusname;
                   // tableData.status = item.status;
                   // tableData.statusname = item.statusname;
                    this.tableData.push(tableData);
                })
            },
            async doGetCoupGrantRuleItem(val){
                const {latitude, longitude} = this.city;
                var _this = this
                var data = {
                    id:val
                }
                const items = await getCoupGrantRuleItem(data);
                this.tableDataItem = [];
                items.data.forEach(item => {
                    const tableData = {};
                    tableData.id = item.id;
                    tableData.salemoney = item.salemoney;
                    tableData.grantmoney = item.grantmoney;
                    tableData.idindex = item.idindex;
                    this.tableDataItem.push(tableData);
                })
            },            
            getyttypeName(val){
                if(val==0){
                    return '百货'
                }else if(val==1){
                    return '超市'
                }else if(val==2){
                    return '异业联盟'
                }else{
                    return ''
                }
            },
            
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.offset = (val - 1)*this.limit;
                this.doGetCoupGrantRuleLists()
            },
            handleEdit(index, row) {
                console.log('handleEdit:',row)
                this.curId = row.id;
                this.selectTable = row;
                this.selectTable.status =  row.status.toString();
              //  this.address.address = row.address;
                this.dialogFormVisible = true;
                this.doGetCoupGrantRuleItem(row.id)
            },
            doAdd() {
                this.selectTable ={status:'0',bLJ:true,bLadder:true}
                this.dialogFormVisible = true;
            },            
            addFood(index, row){
                this.$router.push({ path: 'addGoods', query: { restaurant_id: row.id }})
            },
            async handleDelete(index, row) {
                var _this = this
               _this.doDeleteRule(row.id,index)
            },
            async handleDisabled(index, row,status) {
                var _this = this
               _this.doDisableRule(row.id,status)
            },            
            async querySearchAsync(queryString, cb) {
                if (queryString) {
                    try{
                        const cityList = await searchplace(this.city.id, queryString);
                        if (cityList instanceof Array) {
                            cityList.map(item => {
                                item.value = item.address;
                                return item;
                            })
                            cb(cityList)
                        }
                    }catch(err){
                        console.log(err)
                    }
                }
            },
            AddRule(){
                var data={id:this.curId,salemoney:null,grantmoney:null,idindex:null}
                console.log('data:',data)
                this.tableDataItem.push(data);
                console.log('tableDataItem:',this.tableDataItem)
            },
            
            doSearch(){
                this.currentPage=1;
                this.searchLoading=true;
                this.doGetCoupGrantRuleLists();
                this.searchLoading=false;
            },    
            handleCommand(command,row) {
                //this.$message('click on item ' + command);
                console.log('row:',row)
                this.selectTable = row;
              //  this.address.address = row.address;
                this.dialogFormVisible = true;
            },        
            handleServiceAvatarScucess(res, file) {
                if (res.status == 1) {
                    this.selectTable.image_path = res.image_path;
                }else{
                    this.$message.error('上传图片失败！');
                }
            },
            beforeAvatarUpload(file) {
                const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isRightType) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isRightType && isLt2M;
            },
            async updateRule(){ 
                try{
                    this.$refs['editForm'].validate( async (valid) => {
                        if (valid) {
                            this.selectTable.bj_lj = (this.selectTable.bLJ==true)?1:0;
                            this.selectTable.ladderflag = (this.selectTable.bLadder==true)?1:0;
                            this.selectTable.djsj=null;
                            this.selectTable.items = this.tableDataItem
                            const res = await saveCoupGrantRuleLists(this.selectTable)
                            if (res.Status == 0) {
                                this.dialogFormVisible = false;
                                this.$message({
                                    type: 'success',
                                    message: '保存优惠券发券规则成功'
                                });
                                this.doGetCoupGrantRuleLists();
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: res.msg
                                });
                            }
                        }else{
                            console.log('error submit!!');
                            return;
                        }  
                    });      
                }catch(err){
                    console.log('保存优惠券发券规则失败', err);
                }
            },
            doDeleteRule(id,index) {
                var idList = []
                idList[0] = id           
                this.$confirm('此操作将删除该发券规则, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async() => {
                        const res = await deleteCoupGrantRule(idList);
                        if (res.Status == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除发券规则成功'
                            });
                            this.tableData.splice(index, 1);
                        }else{
                            this.$message({
                                type: 'error',
                                message: res.msg
                            }); 
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '取消删除'
                    });          
                });
            },  
            doDisableRule(id,istatus) {
                var opermsg = ''
                if(istatus==1){
                    opermsg='启用'
                }else{
                    opermsg='禁用'
                }
                var data={id:id,status:istatus}
                this.$confirm('此操作将'+opermsg+'该发券规则, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async() => {
                        const res = await disableCoupGrantRule(data);
                        if (res.Status == 0) {
                            this.$message({
                                type: 'success',
                                message: opermsg+'发券规则成功'
                            });
                            this.doGetCoupGrantRuleLists();
                           // this.tableData.splice(index, 1);
                        }else{
                            this.$message({
                                type: 'error',
                                message: res.msg
                            }); 
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '取消'+opermsg
                    });          
                });
            },              
        },
    }
</script>

<style lang="less">
	@import '../style/mixin';
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .table_container{
        padding: 10px 20px;
    }
    .Pagination{
        display: flex;
        justify-content: flex-start;
        margin-top: 8px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }
    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
    .demo-input-suffix {
        margin-bottom: 15px;
    }
    .demo-input.demo-zh-CN .el-input {
        width: 180px;
    }
    
    .demo-input-suffix .el-input {
        margin-right: 15px;
        width:auto
    }


</style>
